#include<iostream>
#include<algorithm>
#include<queue>
#include<unordered_map>
using namespace std;
using namespace std;

int bfs(string star)
{
	string end = "12345678x";
	queue<string>q;
	unordered_map<string, int>d;
	d[star] = 0;
	q.push(star);
	int dx[] = { -1,0,1,0 };
	int dy[] = { 0,1,0,-1 };
	while (q.size()) {
		auto t = q.front();
		q.pop();
		int distance = d[t];
		if (t == end) {
			return distance;
		}
		int k = t.find("x");
		for (int i = 0; i < 4; i++) {
			int a = dx[i] + k / 3;
			int b = dy[i] + k % 3;
			if (a >= 0 && a < 3 && b >= 0 && b < 3) {
				swap(t[k], t[3 * a + b]);
				if (!d.count(t)) {
					d[t] = distance + 1;
					q.push(t);
				}
				swap(t[k], t[3 * a + b]);
			}
		}
	}
	return -1;
}
int main()
{
	string star;
	for (int i = 0; i < 9; i++) {
		char ch;
		cin >> ch;
		star += ch;
	}
	cout << bfs(star) << endl;
	return 0;
}